<?php
include '../../../Smarty/Smarty.php';
require Yii::getPathOfAlias('common.extensions.SexyTemplate') . '.php';

use \common\models\Wams as Wams;

class AdminController extends controller
{
    // 每页显示记录条数
    private $perPage = 10;
    protected $component_id = 41;
    private $question_level = array(
                                1=>'房务部',
                                2=>'餐饮部',
                                3=>'财务部',
                                4=>'市场营销部',
                                5=>'人力资源部',
                                6=>'工程部',
                                7=>'安保部',
                            );
    public function __construct()
    {
        //判断是否登录
        $this->checkLogin();
        require_once('./../../../PHPExcel/PHPExcel.php');

        $this->cache_time = 0;
    }

    /**
     * 信息页面
     */
    public function index()
    {
        header("Content-Type: text/html; charset=utf-8");
        $page = Yii::app()->request->getParam('page', 1);
        $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        $criteria_e = new CDbCriteria();
        $criteria_c = new CDbCriteria();
        
        //$criteria_c->select = 'count(distinct(user_id)) as count';
        $criteria_c->group = 'user_id';
        $counts = $CrazyAnswerSecondEnter->queryAll($criteria_c);
        $count = count($counts);
        //$count = $counts[0]['count'];
        //$count = $CrazyAnswerSecondEnter->count();
        $criteria_e->group = 'user_id';
        $criteria_e->order = 'add_time ASC';
        $criteria_e->limit = $this->perPage;
        $criteria_e->offset = ($page-1)*$this->perPage;
        $joinInfo = $CrazyAnswerSecondEnter->queryAll($criteria_e);
        foreach ($joinInfo as $k=>$v){
            $log = array();
            $criteria_a = new CDbCriteria();
            $criteria_a->select = 'p.award_type';
            $criteria_a->join = 'LEFT JOIN '.CrazyAnswerSecondAwardLog::model()->tableName().' p ON t.user_id = p.user_id';
            $criteria_a->compare('p.user_id', $v['user_id']);
            $criteria_a->group = 'p.award_type';
            $criteria_a->order = 'p.add_time ASC';
            $data = $CrazyAnswerSecondEnter->queryAll($criteria_a);
            foreach($data as $key=>$val){
                $arr = explode('-', $val['award_type']);
                if($arr[1] == 1){
                    if($arr[0] != 0){
                        $log[$key] = $this->question_level[$arr[0]].$arr[2].'-10元课程';
                    }else{
                        $log[$key] = '分享既得-通用课程';
                    }
                }else if($arr[1] == 2){
                    $log[$key] = '分享既得-通用课程';
                }
            }
            $joinInfo[$k]['prizeLog'] = array_unique($log);
        }
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '?';
        $this->assign([
            'pagination' => $this->getPagination($page, ceil($count / $this->perPage), $url),
            'joinInfo' => $joinInfo,
            'admin' => isset($_COOKIE['xzAdmin'])?'xianzhi':NULL,
        ]);
        $this->display('audit.html');
    }

    /**
     * 统计页面
     */
    public function count(){
        //访问数据
        $ContestStatistic_new  = new ContestStatistic_new();
        $criteria = new CDbCriteria();
        $criteria->select = 'page,count(id) as count';
        $criteria->compare('component_id', $this->component_id);
        $criteria->group = 'page';
        $contest = $ContestStatistic_new->queryAll($criteria);
        $contests = array();
        foreach($contest as $k=>$v){
            $contests[$v['page']] = $v['count'];
        }

        $ContestButton = new ContestButton();
        $criteria_b = new CDbCriteria();
        $criteria_b->select = 'button,count(id) as count';
        $criteria_b->compare('component_id', $this->component_id);
        $criteria_b->group = 'button';
        $button = $ContestButton->queryAll($criteria_b);
        $button_num = array();
        foreach($button as $k=>$v){
            $button_num[$v['button']] = $v['count'];
        }
        

        //分享数据
        $statData['shareFir'] = XzShare_new::model()->count("component_id = ".$this->component_id." and type = 1");
        $statData['shareFirQ'] =  XzShare_new::model()->count("component_id = ".$this->component_id." and type = 2");
        
        //活动数据
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        
        $criteria_c = new CDbCriteria();
        $criteria_c->group = 'user_id';
        $counts = $CrazyAnswerSecondEnter->queryAll($criteria_c);
        $count = count($counts);
        $activities['enter'] = $count;
        
        $criteria_u = new CDbCriteria();
        $criteria_u->group = 'openid';
        $counts = $CrazyAnswerSecondUser->queryAll($criteria_u);
        $count = count($counts);
        $activities['user'] = $count;

        $data = $CrazyAnswerSecondUser->queryAll();
        if(empty($data)){
            $activities['title'] = 0;
        }else{
            $num = 0;
            foreach($data as $k=>$v){
                if($v['the_shortest_time'] <= 150 && $v['the_shortest_time'] != 0){
                    $num++;
                }
            }
            $activities['title'] = $num;
        }

        $this->assign([
            'admin' => isset($_COOKIE['xzAdmin'])?'xianzhi':NULL,
            'button_num' => $button_num,
            'statData' => $statData,
            'activities' => $activities,
            'contests' => $contests
        ]);
        $this->display('count.html');
    }

    // phpexcel导出
    public function export(){
        $obj = new PHPExcel();
        $alignment = new PHPExcel_Style_Alignment();
        $obj->setActiveSheetIndex(0);
        //设置宽度
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(6);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(12);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(26);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        
        //水平居中
        $obj->getActiveSheet()->getStyle('A')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $obj->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $obj->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $obj->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $obj->getActiveSheet()->getStyle('E')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        
        //垂直居中
        $obj->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $obj->getActiveSheet()->getStyle('B')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $obj->getActiveSheet()->getStyle('C')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $obj->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $obj->getActiveSheet()->getStyle('E')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $obj->getActiveSheet()->setCellValue('A1', 'ID');
        $obj->getActiveSheet()->setCellValue('B1', '姓名');
        $obj->getActiveSheet()->setCellValue('C1', '手机');
        $obj->getActiveSheet()->setCellValue('D1', '中奖记录');
        $obj->getActiveSheet()->setCellValue('E1', '报名时间');
        

        $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        
        $criteria_e = new CDbCriteria();
        $criteria_e->group = 'user_id';
        $criteria_e->order = 'add_time ASC';
        $joinInfo = $CrazyAnswerSecondEnter->queryAll($criteria_e);
        foreach ($joinInfo as $k=>$v){
            $log = array();
            $criteria_a = new CDbCriteria();
            $criteria_a->select = 'p.award_type';
            $criteria_a->join = 'LEFT JOIN '.CrazyAnswerSecondAwardLog::model()->tableName().' p ON t.user_id = p.user_id';
            $criteria_a->compare('p.user_id', $v['user_id']);
            $criteria_a->group = 'p.award_type';
            $criteria_a->order = 'p.add_time ASC';
            $data = $CrazyAnswerSecondEnter->queryAll($criteria_a);
            foreach($data as $key=>$val){
                $arr = explode('-', $val['award_type']);
                if($arr[1] == 1){
                    if($arr[0] != 0){
                        $log[$key] = $this->question_level[$arr[0]].$arr[2].'-10元课程';
                    }else{
                        $log[$key] = '分享既得-通用课程';
                    }
                }else if($arr[1] == 2){
                    $log[$key] = '分享既得-通用课程';
                }
            }
            $joinInfo[$k]['prizeLog'] = array_unique($log);
        } 

        $i = 2;
        foreach($joinInfo as $v){
            $prizeLog = "";
            $obj->getActiveSheet()->setCellValue('A' . $i, $v['id']);
            $obj->getActiveSheet()->setCellValue('B' . $i, $v['name']);
            $obj->getActiveSheet()->setCellValue('C' . $i, $v['tel']);
            foreach($v['prizeLog'] as $val){
                $prizeLog .= "\n".$val;
            }
            $obj->getActiveSheet()->setCellValue('D' . $i, $prizeLog);
            $obj->getActiveSheet()->getStyle('D' . $i)->getAlignment()->setWrapText(true);
            $obj->getActiveSheet()->setCellValue('E' . $i, $v['add_time']);
            $i ++;
        }

        header('Content-Type : application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="'.'IHMA疯狂小答人第二季-'.date("Ymd").'.xls"');
        $objWriter= PHPExcel_IOFactory::createWriter($obj,'Excel5');
        $objWriter->save('php://output');
    }

    //获取分页字符串
    private function getPagination($current, $all, $url)
    {

        if ($all <= 0) {
            return "";
        }
        if ($current > $all || $current <= 0) {
            $current = 1;
        }

        $str = '<ul class="pagination pagination-sm no-margin pull-right">';
        if ($current <= 1) {
            $str .= "<li class=\"disabled\"><span>«</span></li>";
        } else {
            $str .= '<li><a href="' . $url . 'page=' . ($current - 1) . '"><span>«</span></a></li>';
        }
        if ($current >= 7) {
            $str .= '<li><a href="' . $url . 'page=1">1</a></li><li><a href="' . $url . 'page=2">2</a></li><li class="disabled"><span>...</span></li>';
            $leftMore = $current > $all - 5 ? $current - ($all - 5) : 0;
            for ($i = $current - 3 - $leftMore; $i < $current; $i++) {
                if ($i <= 2) {
                    continue;
                }
                $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
            }
        }
        if ($current <= 6) {
            for ($i = 1; $i < $current; $i++) {
                $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
            }
        }
        //当前页
        $str .= '<li class="active"><a href="' . $url . 'page=' . $current . '">' . $current . '</a></li>';
        if ($current + 5 >= $all) {
            for ($i = $current + 1; $i <= $all; $i++) {
                $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
            }

        } else if ($current <= 6) {
            for ($i = $current + 1; $i <= 8; $i++) {
                if ($i > $all) {
                    break;
                }
                $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
            }
        } else {
            for ($i = $current + 1; $i <= $current + 3; $i++) {
                if ($i > $all) {
                    break;
                }
                $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
            }
        }
        if ($current <= $all - 6) {

            $str .= '<li class="disabled"><span>...</span></li><li><a href="' . $url . 'page=' . ($all - 1) . '">' . ($all - 1) . '</a></li><li><a href="' . $url . '?page=' . $all . '">' . $all . '</a></li>';
        }
        if ($current < $all) {
            $str .= '<li><a href="' . $url . 'page=' . ($current + 1) . '"><span>»</span></a></li>';
        } else {
            $str .= '<li class="disabled"><span>»</span></li>';
        }
        $str .= '</ul>';
        return $str;
    }

    private function checkLogin(){
        if(!isset($_COOKIE['xzAdmin'])|| !$_COOKIE['xzAdmin'] == md5('xianzhi'.md5(date('ymd')))){
            //header("Location:http://wams.veryeast.cn/activity/8anniversary/day_wampsadmin/login.php");
            header("Location:http://crazy_second.dev/day_wampsadmin/login.php");
            exit();
        }
    }
    
    public function clear(){
        $usql[0] = "truncate table wams_crazy_answer_second_enter";
        $usql[1] = "truncate table wams_crazy_answer_second_award_log";
        $usql[2] = "truncate table wams_crazy_answer_second_user";
        $usql[3] = "truncate table wams_contest_button";
        $usql[5] = "delete from wams_xz_share where component_id=41";
        $usql[4] = "delete from wams_contest_statistic where component_id=41";
        foreach($usql as $k=>$v){
            CrazyAnswerSecondUser::model()->getDbConnection()->createCommand($v)->execute();
        }
        
        $this->ajaxTip(1,'');
    }

}


$controller = new AdminController();
$action = isset($_GET['a']) ? trim($_GET['a']) : 'index';
$controller->$action();
